<?php 
class CategoryController extends CommonController{
	private $model;
	public function __init(){
		parent::__init();
		$this->model=K("Category");
	}
	
	
	
	public function index(){
		$data=$this->model->order('sort asc')->all();
		$data=Data::tree($data, 'cname');	
//		p($data);die;
		$this->assign("data",$data);
		$this->display();
	}
	
	
	/**
	 * 添加顶级分类
	 */
	 public function add(){
	 	if(IS_POST){
        	if(!$this->model->addcate()) $this->error($this->model->error);
			$this->success("添加成功");
        }
	 	//查询所有的类型
	 	$data=K('Type')->all();
		$this->assign("data",$data);
        
	 	$this->display();
	 }
	 /**
	  * 排序
	  */
	  public function catesort(){
	  	if(IS_POST){
        	if(!$this->model->sortcate()) $this->error($this->model->error);
			
			$this->success("排序成功");
        }
	  }
	 /**
	  * 添加子分类
	  */
	  public function addsoncate(){
	  	if(IS_POST){
	  		if(!$this->model->addson()) $this->error($this->model->error);
			$this->success("添加成功");			
	  	}
		//查询所有的类型
	 	$data=K('Type')->all();
		$this->assign("data",$data);
		$this->display();
		
	  }
	  /**
	   * 编辑
	   */
	   public function edit(){
	   	if(IS_POST){
	  		if(!$this->model->editcate()) $this->error($this->model->error);
			$this->success("修改成功");			
	  	}
		//查询所有的类型
	 	$data=K('Type')->all();
		$this->assign("data",$data);
		//获得旧数据
		$cid=Q("get.cid");
		$oldData=$this->model->where("cid={$cid}")->find();
		$this->assign('oldData',$oldData);		
		$this->display();
	   }
	   /**
	    * 删除
	    */
	   public function del(){
	   	$cid=Q("get.cid","","intval");
//		p($cid);die;
          $good=M("goods")->where("category_cid={$cid}")->find();
		  if($good){
		  	$this->error("请先删除商品");
		  }
		//如果有子集先删除子集
		$son=$this->model->where("pid={$cid}")->all();
		if($son){
			$this->error("请先删除子集");
		}
		
		//删除分类
		$this->model->where("cid={$cid}")->delete();
		$this->success("删除成功");
		
		
	   }
	  
	 
	 
}



 ?>